<?php

namespace app\teacher\controller\v1;

use app\common\controller\BaseController;
use think\Controller;
use think\Db;
use think\Request;
use app\teacher\model\Teacher as TeacherModel;
use app\teacher\model\TeacherWithdraw as TeacherWithdrawModel;
use app\teacher\model\TeacherMoneyLog as TeacherMoneyLogModel;

class Money extends BaseController
{
    /**
     * 申请提现
     */
    public function create()
    {
        $this->isPost();
        $money = $this->notEmpty('money');
        $type = $this->notEmpty('type');
        $data = $this->request->post();
        $teacher = TeacherModel::find($this->teacherId);
        if (!$teacher) {
            $this->errorMsg(20000);
        }
        if ($teacher->verify <= 1) {
            $this->errorMsg(20002);
        }
        if ($teacher->money < $money) {
            $this->errorMsg(20001);
        }
        Db::startTrans();
        try {
            //提现
            TeacherWithdrawModel::add($teacher, $data);
            //账户明细
            TeacherMoneyLogModel::add($teacher, -$data['money'], 2);
            //更新账号余额
            $teacher->setDec('money', $money);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
        isset($e) ? $e->getMessage() : $this->success();
    }

    /**
     * 账户明细
     */
    public function log()
    {
        $size = $this->request->get('size');
        $logs = TeacherMoneyLogModel::getLog($this->teacherId, $size);
        $logs->total() ? $this->success('', [
            'logs' => $logs->items(),
            'total' => $logs->total()
        ]) : $this->notFoundData();
    }

    /**
     * 提现记录
     */
    public function withdraw()
    {
        $size = $this->request->get('size');
        $logs = TeacherWithdrawModel::getByTeacherId($this->teacherId, $size);
        $logs->items() ? $this->success('', [
            'logs' => $logs->items(),
            'total' => $logs->total()
        ]) : $this->notFoundData();
    }
}
